package com.wingsfrog.travel.service.impl;

import com.wingsfrog.travel.controller.dto.response.TaskResDto;
import com.wingsfrog.travel.modules.dao.*;
import com.wingsfrog.travel.modules.entity.Task;
import com.wingsfrog.travel.modules.entity.TeamInfo;
import com.wingsfrog.travel.modules.entity.TeamTask;
import com.wingsfrog.travel.modules.entity.UserTeamRel;
import com.wingsfrog.travel.service.TaskService;
import com.wingsfrog.travel.service.TeamHintService;
import com.wingsfrog.travel.service.TeamService;
import com.wingsfrog.travel.service.TeamTaskService;
import com.wingsfrog.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by rankin on 16/3/30.
 */
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    TaskDao taskDao;
    @Autowired
    TeamTaskDao teamTaskDao;
    @Autowired
    TeamDao teamDao;
    @Autowired
    TeamTaskService teamTaskService;
    @Autowired
    HintDao hintDao;
    @Autowired
    TeamHintDao teamHintDao;
    @Autowired
    TeamService teamService;
    @Autowired
    UserTeamRelDao userTeamRelDao;
    @Autowired
    TeamHintService teamHintService;

    @Override
    public TeamTask accpetTask() throws Exception {
        UserTeamRel rel = userTeamRelDao.findByUserIdAndIsEnable(SessionUtil.getUserId(), true);
        if (rel == null) throw new Exception("not data found");
        Integer mainTaskId = rel.getMainTaskId();

        //接收分配的任务
        Integer sequenceToAccept;

        TeamInfo team = teamService.findTeamByMainTaskAndUser(mainTaskId, SessionUtil.getUserId());

        Integer teamId = team.getId();

        //找到最后一个任务，确认是已完成，并且不是终结任务
        TeamTask lastTask = teamTaskService.getLastTeamTask(teamId);
        if (lastTask == null) sequenceToAccept = 1;
        else if (lastTask.getFinished() == 0) throw new Exception("当前任务未完成");
        else sequenceToAccept = lastTask.getSequence() + 1;
        //把任务的内容插入到teamtask中
        TeamTask teamTask = teamTaskService.acceptTaskByTeamIdAndMainTaskIdAndSequence(teamId, mainTaskId, sequenceToAccept);

        //把第一个线索插入到teamhint中
        teamHintService.acceptHintByTeamTaskIdAndTaskId(teamTask.getTaskId(), teamTask.getId());
        return teamTask;
    }
    @Override
    public List getTaskList(Integer userId) {
        Iterable<Task> itTask = taskDao.findAll();
        List<TaskResDto> resList = new ArrayList<>();
        itTask.forEach((task) -> {
            resList.add(getTaskResDtoFromTaskEntity(task));
        });
        return resList;
    }

    private TaskResDto getTaskResDtoFromTaskEntity(Task task){
        TaskResDto resDto = new TaskResDto();
        resDto.setId(task.getId());
        resDto.setTaskName(task.getTaskName());
        resDto.setTaskDescription(task.getTaskDescription());
        return resDto;
    }
}
